/*Script Part1: for game initialization and game tab */

	//global variables
 var currentGameID = null;
 var currentDesignerUserName;
 var currentDesignerID;
 var newGame;
 var currentGameDetails;
 var curMapItemMarkers = new Array();
 var curMapQuestMarkers = new Array();
 var curMapNPCMarkers = new Array();
 var currentEdittingDialogNPCID;
 var currentDialogNodes;
 var currentDialogEdges;
 var currentBranchNum;
 var currentQuestNum;
 var questOrderArray = new Array();
 var currentTriggerID;
 var currentItemHeaders = new Array();
 var currentNPCHeaders = new Array();
 var currentQuestHeaders = new Array();

 //game init and game tab init
 $(document).ready(
   function() {

	   //start Game & Designer init
	   currentDesignerUserName = $("#username").val();
	   currentDesignerID = $("#designerID").val();
	   GameService.retrieveGameList(currentDesignerID, retrieveGameListCB);
	   $("#loadedGameArea").hide();
	   //$("#questOrderPanel").hide();
	   //end Game &init

	   // Start Tabs
	   $('#tabs').tabs({ selected : 0, disabled : [ 1, 2] });
	   // $('#tabs').fadeIn(5000);
	   
	   $("#openQuestOrderPanelBtn").button({disabled:true});

	   $(".tabBtn").each(function() {
		   $(this).click(function() {
			   $(".gPanel").each(function(i, element) {
				   $(element).dialog("close");
			   });
			   if ($(this).is("#mapTabBtn")) {
				   $("#mapPropertyPanel").dialog("open");
				   $("#gameObjsAccordionsPanel").dialog("open");

				   setTimeout(function() {
					   google.maps.event.trigger(map, 'resize');
				   }, 2000);
			   }
			   if ($(this).is("#dialogTabBtn")) {
				   $("#npcDialogsPropertyPanel").dialog("open");
				   $("#npcDialogsAccordionsPanel").dialog("open");

				   setTimeout(function() {
					   google.maps.event.trigger(map, 'resize');
				   }, 2000);
			   }
		   });
	   });

	   // End Tabs
	   
	   //Start Button Styles
	   $('button').button();
	   
    $("#createItemBtn").button({icons: {primary: "ui-icon-plusthick"}});
    $("#modifyItemBtn").button({icons:{primary: "ui-icon-check"}});   
    $("#deleteItemBtn").button({icons:{primary: "ui-icon-trash"}});
    
    $("#createQuestBtn").button({icons: {primary: "ui-icon-plusthick"}});
    $("#modifyQuestBtn").button({icons:{primary: "ui-icon-check"}});   
    $("#deleteQuestBtn").button({icons:{primary: "ui-icon-trash"}});
    
    $("#createNPCBtn").button({icons: {primary: "ui-icon-plusthick"}});
    $("#modifyNPCBtn").button({icons:{primary: "ui-icon-check"}});   
    $("#deleteNPCBtn").button({icons:{primary: "ui-icon-trash"}});
    
    //End Button Styles
    	$("#publishGameBtn").click(function() {
    		GameService.publishGame(currentGameID);
    	});


	   $("#createGameModalDialog").dialog(
	     { autoOpen : false, resizable : false, closeOnEscape : false, hide : "slow", modal : true,
	      title : "Create Your Game"
	     });
	   
	   $("#uploadModalDialog").dialog(
	     { autoOpen : false, resizable : false, closeOnEscape : false, hide : "slow", modal : true,
	     	height:400,width:350,
	      title : "Upload the picture",  buttons: {
	       "Upload": function() {
	        $("#upload_frame").contents().find("#pic").attr("src","loading.gif");
	        $("#gameID").val(currentGameID);
	        $("#uploadForm").submit();
	       },
	     "Back": function() {
	     	$("#file").val("");
	        $(this).dialog("close");
	     }
	   }
	  														
	     });
	   
	     $("#gameRuleModalDialog").dialog(
	     { autoOpen : false, resizable : false, closeOnEscape : false, hide : "slow", modal : true,
	     	height:580,width:500,
	      title : "Game rule editor",  buttons: {
	     "Back": function() {
	        $(this).dialog("close");
	     }
	   }
	  														
	     });
	   
	   initButtonsEvents();

   });

 function initButtonsEvents() {
	 
	 $("#openCreateGameDialogBtn").click(function() {
		 if (!$("#createGameModalDialog").dialog("isOpen")) {
			 $("#createGameModalDialog").dialog("open");
			 $("#createGameModalDialog").dialog("option", "position", "center");
		 }
	 });
	 
	 $("#gameIconBtn").click(function() {
		 if (!$("#uploadModalDialog").dialog("isOpen")) {
		 	$("#upload_frame").contents().find("#pic").attr("src","loading.gif");
			 $("#uploadModalDialog").dialog("open");
			 $("#uploadModalDialog").dialog("option", "position", "center");
			 $("#requestUpload").val("gameIcon");
			 $("#gameObjID").val(currentGameID);
			 MediaService.previewUploadImages( $("#requestUpload").val(),
			 		$("#gameObjID").val(),function(data) {
			 	$("#upload_frame").contents().find("#pic").attr("src",data);
			 });
		 }
	 });
	 
	 $("#gameCoverBtn").click(function() {
		 if (!$("#uploadModalDialog").dialog("isOpen")) {
		 	$("#upload_frame").contents().find("#pic").attr("src","loading.gif");
			 $("#uploadModalDialog").dialog("open");
			 $("#uploadModalDialog").dialog("option", "position", "center");
			 $("#requestUpload").val("gameCover");
			 $("#gameObjID").val(currentGameID);
			 MediaService.previewUploadImages( $("#requestUpload").val(),
			 		$("#gameObjID").val(),function(data) {
			 	if(data!=null && data!="") {
			 	$("#upload_frame").contents().find("#pic").attr("src",data);
			 	}
			 });
			 
			 
		 }
	 });
	 
	 $("#itemPickableTriggerBtn").click(function() {
		 if (!$("#gameRuleModalDialog").dialog("isOpen")) {
			 $("#gameRuleModalDialog").dialog("open");
			 $("#gameRuleModalDialog").dialog("option", "position", "center");
			 $("#conditionTable tr:gt(0)").remove();
			 $("#triggerDescription").html("Player can pick up this item if following conditions meet:");
			 var objID = $(".selectedItemRow").first().attr("id");
			 $("#gameObjID").val(objID);
			 var trigger = {actionObjectID:objID,actionType:"itempick",gameID:currentGameID};
			 GameRuleService.getGameObjectTrigger(trigger, function(data) {
				 currentTriggerID = data.triggerID;
				 $("#edTextAfterTrigger").val(data.textAfterTrigger);
				 GameRuleService.retrieveConditionList(currentTriggerID,retrieveConditionListCB);
			 });

		 }
	 });
	 
	  $("#npcChattableTriggerBtn").click(function() {
		 if (!$("#gameRuleModalDialog").dialog("isOpen")) {
			 $("#gameRuleModalDialog").dialog("open");
			 $("#gameRuleModalDialog").dialog("option", "position", "center");
			 $("#conditionTable tr:gt(0)").remove();
			 $("#triggerDescription").html("Player can have a dialog with this NPC if following conditions meet:");
			 var objID = $(".selectedNPCRow").first().attr("id");
			 $("#gameObjID").val(objID);
			 var trigger = {actionObjectID:objID,actionType:"npcchat",gameID:currentGameID};
			 GameRuleService.getGameObjectTrigger(trigger, function(data) {
				 currentTriggerID = data.triggerID;
				 $("#edTextAfterTrigger").val(data.textAfterTrigger);
				 GameRuleService.retrieveConditionList(currentTriggerID,retrieveConditionListCB);
			 });

		 }
	 });
	  
	 	  $("#questStartTriggerBtn").click(function() {
		 if (!$("#gameRuleModalDialog").dialog("isOpen")) {
			 $("#gameRuleModalDialog").dialog("open");
			 $("#gameRuleModalDialog").dialog("option", "position", "center");
			 $("#conditionTable tr:gt(0)").remove();
			 $("#triggerDescription").html("Player can start this quest if following conditions meet:");
			 var objID = $(".selectedQuestRow").first().attr("id");
			 $("#gameObjID").val(objID);
			 var trigger = {actionObjectID:objID,actionType:"queststart",gameID:currentGameID};
			 GameRuleService.getGameObjectTrigger(trigger, function(data) {
				 currentTriggerID = data.triggerID;
				 $("#edTextAfterTrigger").val(data.textAfterTrigger);
				 GameRuleService.retrieveConditionList(currentTriggerID,retrieveConditionListCB);
			 });

		 }
	 });
	 	  
	 	 $("#questCompleteTriggerBtn").click(function() {
		 if (!$("#gameRuleModalDialog").dialog("isOpen")) {
			 $("#gameRuleModalDialog").dialog("open");
			 $("#gameRuleModalDialog").dialog("option", "position", "center");
			 $("#conditionTable tr:gt(0)").remove();
			 $("#triggerDescription").html("Player can complete this quest if following conditions meet:");
			 var objID = $(".selectedQuestRow").first().attr("id");
			 $("#gameObjID").val(objID);
			 var trigger = {actionObjectID:objID,actionType:"questcomplete",gameID:currentGameID};
			 GameRuleService.getGameObjectTrigger(trigger, function(data) {
				 currentTriggerID = data.triggerID;
				 $("#edTextAfterTrigger").val(data.textAfterTrigger);
				 GameRuleService.retrieveConditionList(currentTriggerID,retrieveConditionListCB);
			 });

		 }
	 });
	  
	 
	 $("#modifyTextAfterTriggerBtn").click(function() {
		 var modTrigger = {triggerID : currentTriggerID, textAfterTrigger: $("#edTextAfterTrigger").val()};
		 GameRuleService.modifyTriggerDetails(modTrigger,function() {
		       $("#mapTabMessage").writeAlert("Modified Sucessfully").fadeIn("slow").delay(3500)
		         .fadeOut("slow");
		 });
	 });
	 
	 $("#createConditionBtn").click(function() {
		 
		 var conditionType = $("#conditionTypeSelect").val();
		 var conditionTypeText = $("#conditionTypeSelect option:selected").text();
		 var conditionTypeTD = "<td colType='conditionType'>" + conditionTypeText + "</td>";
		 var paramXTD = "<td colType='paramX'>";
		 if(conditionType == "itempick") {
			 if(currentItemHeaders.length == 0) {
				    $("#mapTabMessage").writeError(
				      "Cannot create this condition because no items are in the editor.").fadeIn("slow").delay(
				      3500).fadeOut("slow");
				    return;
			 }
			 paramXTD += "<select>";
			 for(var i = 0; i < currentItemHeaders.length; ++i) {
				 var optionStr =  "<option value='"+ currentItemHeaders[i].id +
				 "'>"+ currentItemHeaders[i].title + "</option>";
				 paramXTD += optionStr;
			 }
			 paramXTD += "</select>";
		 } else if(conditionType == "npcchat" || conditionType == "npcgreet") {
			 if(currentNPCHeaders.length == 0) {
				    $("#mapTabMessage").writeError(
				      "Cannot create this condition because no NPCs are in the editor.").fadeIn("slow").delay(
				      3500).fadeOut("slow");
				    return;
			 }
			 paramXTD += "<select>";
			 for(var i = 0; i < currentNPCHeaders.length; ++i) {
				 var optionStr =  "<option value='"+ currentNPCHeaders[i].id +
				 "'>"+ currentNPCHeaders[i].title + "</option>";
				 paramXTD += optionStr;
			 }
			 paramXTD += "</select>";
		 } else if(conditionType == "itemnum") {
			 paramXTD += "<input type='text' style='width:100%;border:1px #69C solid'/>";
		 } else if(conditionType == "queststart" || conditionType == "questcomplete") {
			 if(currentQuestHeaders.length == 0) {
				    $("#mapTabMessage").writeError(
				      "Cannot create this condition because no Quests are in the editor.").fadeIn("slow").delay(
				      3500).fadeOut("slow");
				    return;
			 }
			 paramXTD += "<select>";
			 for(var i = 0; i < currentQuestHeaders.length; ++i) {
				 var optionStr =  "<option value='"+ currentQuestHeaders[i].id +
				 "'>"+ currentQuestHeaders[i].title + "</option>";
				 paramXTD += optionStr;
			 }
			 paramXTD += "</select>";
		 } 
		 paramXTD += "</td>";
		 
		 var paramYTD = "<td colType='paramY'>";
		 
		 if(conditionType == "itemnum") {
			 paramYTD += "<input type='text' style='width:100%;border:1px #69C solid'/>";
		 }
		 paramYTD += "</td>";
		 
		 var confirmTD = "<td colType='confirm'><a class='conditionConfirm' href='#'><img src='confirm.png'/></a></td>";
		 var deleteTD = "<td colType='delete'><a class='conditionDelete' href='#'><img src='delete.png'/></a></td>";
		 
		 $("#conditionTable").append("<tr>" + conditionTypeTD + paramXTD + 
			 paramYTD + confirmTD + deleteTD + "</tr>");
			 
			 

		 $(".conditionConfirm").each(function () {
			 $(this).click(function() {
			 if($(this).parent().parent().attr("save") != null) return;
			 $(this).parent().parent().attr("save","save");
			
			 var paramX = "";
			 var paramY = "";
			 if(conditionType == "itempick") {
				 paramX = $(this).parent().parent().find("td:[colType=paramX] option:selected").val();
				 $(this).parent().parent().find("td:[colType=paramX]").html($(this).parent().parent().find("td:[colType=paramX] option:selected").text());
			 } else if(conditionType == "npcchat") {
				 paramX = $(this).parent().parent().find("td:[colType=paramX] option:selected").val();
				 $(this).parent().parent().find("td:[colType=paramX]").html($(this).parent().parent().find("td:[colType=paramX] option:selected").text());
			 } else if(conditionType == "npcgreet") {
				 paramX = $(this).parent().parent().find("td:[colType=paramX] option:selected").val();
				 $(this).parent().parent().find("td:[colType=paramX]").html($(this).parent().parent().find("td:[colType=paramX] option:selected").text());
			 }else if(conditionType == "itemnum") {
				 paramX = $(this).parent().parent().find("td:[colType=paramX] input").val();
				 $(this).parent().parent().find("td:[colType=paramX]").html($(this).parent().parent().find("td:[colType=paramX] input").val());
			 } else if(conditionType == "queststart") {
				 paramX = $(this).parent().parent().find("td:[colType=paramX] option:selected").val();
				 $(this).parent().parent().find("td:[colType=paramX]").html($(this).parent().parent().find("td:[colType=paramX] option:selected").text());
			 } else if(conditionType == "questcomplete") {
				 paramX = $(this).parent().parent().find("td:[colType=paramX] option:selected").val();
				 $(this).parent().parent().find("td:[colType=paramX]").html($(this).parent().parent().find("td:[colType=paramX] option:selected").text());
			 }
			 
			 if(conditionType == "itemnum") {
				 paramY = $(this).parent().parent().find("td:[colType=paramY] input").val();
				 $(this).parent().parent().find("td:[colType=paramY]").html($(this).parent().parent().find("td:[colType=paramY] input").val());
			 }
			 
			 var thisObj = $(this);
			 
			 var condition = {conditionType: conditionType,
			                  paramX: paramX, paramY : paramY,
			 				triggerID : currentTriggerID};
			 GameRuleService.addConditionForTrigger(condition,function(data) {
				 thisObj.parent().parent().attr("conditionID",data);
				 
			 });
			 
			 	$(this).unbind("click");
			 	$(this).find("img").remove();
			 });
		 });
		 
		  $(".conditionDelete").each( function() {
			  $(this).click(function() {
			 if($(this).parent().parent().attr("save") != null) {
				 GameRuleService.deleteConditionForTrigger($(this).parent().parent().attr("conditionID"));
			 } 
				 $(this).parent().parent().remove();
			 
		 });
			 });
		 
	 });
	 
	 $("#itemIconBtn").click(function() {
		 if (!$("#uploadModalDialog").dialog("isOpen")) {
		 	$("#upload_frame").contents().find("#pic").attr("src","loading.gif");
			 $("#uploadModalDialog").dialog("open");
			 $("#uploadModalDialog").dialog("option", "position", "center");
			 $("#requestUpload").val("itemIcon");
			 var objID = $(".selectedItemRow").first().attr("id");
			 $("#gameObjID").val(objID);
			 MediaService.previewUploadImages( $("#requestUpload").val(),
			 		$("#gameObjID").val(),function(data) {
			 	$("#upload_frame").contents().find("#pic").attr("src",data);
			 });
		 }
	 });
	 
	 	 $("#questIconBtn").click(function() {
		 if (!$("#uploadModalDialog").dialog("isOpen")) {
		 	$("#upload_frame").contents().find("#pic").attr("src","loading.gif");
			 $("#uploadModalDialog").dialog("open");
			 $("#uploadModalDialog").dialog("option", "position", "center");
			 $("#requestUpload").val("questIcon");
			 var objID = $(".selectedQuestRow").first().attr("id");
			 $("#gameObjID").val(objID);
			 MediaService.previewUploadImages( $("#requestUpload").val(),
			 		$("#gameObjID").val(),function(data) {
			 	$("#upload_frame").contents().find("#pic").attr("src",data);
			 });
		 }
	 });
	 
	 $("#npcIconBtn").click(function() {
		 if (!$("#uploadModalDialog").dialog("isOpen")) {
		 	$("#upload_frame").contents().find("#pic").attr("src","loading.gif");
			 $("#uploadModalDialog").dialog("open");
			 $("#uploadModalDialog").dialog("option", "position", "center");
			 $("#requestUpload").val("npcIcon");
			 var objID = $(".selectedNPCRow").first().attr("id");
			 $("#gameObjID").val(objID);
			 MediaService.previewUploadImages( $("#requestUpload").val(),
			 		$("#gameObjID").val(),function(data) {
			 	$("#upload_frame").contents().find("#pic").attr("src",data);
			 });
		 }
	 });
	 
	 $("#itemContainedMediaBtn").click(function() {
		 if (!$("#uploadModalDialog").dialog("isOpen")) {
		 	$("#upload_frame").contents().find("#pic").attr("src","loading.gif");
			 $("#uploadModalDialog").dialog("open");
			 $("#uploadModalDialog").dialog("option", "position", "center");
			 $("#requestUpload").val("itemContainedMedia");
			 var objID = $(".selectedItemRow").first().attr("id");
			 $("#gameObjID").val(objID);
			 MediaService.previewUploadImages( $("#requestUpload").val(),
			 		$("#gameObjID").val(),function(data) {
			 	$("#upload_frame").contents().find("#pic").attr("src",data);
			 });
		 }
	 });
	 
	 $("#npcFigureBtn").click(function() {
		 if (!$("#uploadModalDialog").dialog("isOpen")) {
		 	$("#upload_frame").contents().find("#pic").attr("src","loading.gif");
			 $("#uploadModalDialog").dialog("open");
			 $("#uploadModalDialog").dialog("option", "position", "center");
			 $("#requestUpload").val("npcFigure");
			 var objID = $(".selectedNPCRow").first().attr("id");
			 $("#gameObjID").val(objID);
			 MediaService.previewUploadImages( $("#requestUpload").val(),
			 		$("#gameObjID").val(),function(data) {
			 	$("#upload_frame").contents().find("#pic").attr("src",data);
			 });
		 }
	 });
	 
	 $("#cancelCreateGameBtn").click(function() {
		
			 $("#createGameModalDialog").dialog("close");

	 });
	 
	 $("#uploadBackBtn").click(function() {
			
		 $("#uploadModalDialog").dialog("close");

 });

	 $("#createGameBtn").click(
	   function() {
		   newGame = { designerID : currentDesignerID,
		    internalDescription : $("#createInternalDescription").val(),
		    gameName : $("#createGameName").val() };
		   GameService.createNewGame(newGame, createNewGameCB);
	   });
	 
	 $("#loadGameBtn").click(function() {
		 var selectedGameID = $("#gameList").val();
		 if(selectedGameID!=currentGameID) {
		 GameService.loadGameDetails(selectedGameID, loadGameDetailsCB);
		 if(currentGameID!=null) {
			 clearPreviousGameData();
		 }
		 ItemService.retrieveItemList(selectedGameID, retrieveItemListCB);
		 NPCService.retrieveNPCList(selectedGameID, retrieveNPCListCB);
		 QuestService.retrieveQuestList(selectedGameID, retrieveQuestListForInitialCB);
		 $("#openQuestOrderPanelBtn").button({disabled:false});
		 $("#loadedGameArea").show();
		 }
	 });

	 $("#reloadGameBtn").click(function() {
		 GameService.loadGameDetails(currentGameID, loadGameDetailsCB);
	 });

	 $("#modifyGameBtn").click(
	   function() {
		   var game = { gameID : currentGameID, designerID : currentDesignerID,
		    gameName : $("#edGameName").val(), publishTitle : $("#edPublishTitle").val(),
		    publishDescription : $("#edPublishDescription").val(),
		    internalDescription : $("#edInternalDescription").val(), introduction : $("#edIntroduction").val(),
		    ending : $("#edEnding").val(), designStatus : $("#designStatus").val() };
		   GameService.modifyGameDetails(game, modifyGameDetailsCB);
	   });
	 


 }
 
 function clearPreviousGameData() {
	 //Todo!!!
 }
 
 
function retrieveConditionListCB(data) {
	for(var i = 0; i < data.length; ++i) {
		if(data[i].paramX == null) data[i].paramX = "";
		if(data[i].paramY == null) data[i].paramY = "";
		var conditionTypeTD = "<td colType='conditionType'>" + data[i].conditionType + "</td>";
		var paramXTD = "<td colType='paramX'>"+data[i].paramX+"</td>";
		var paramYTD = "<td colType='paramY'>"+data[i].paramY+"</td>";
		var confirmTD = "<td colType='confirm'></td>";
		 var deleteTD = "<td colType='delete'><a class='conditionDelete' href='#'><img src='delete.png'/></a></td>";
		 
		 $("#conditionTable").append("<tr save='save' conditionID='"+data[i].conditionID+"'>" + conditionTypeTD + paramXTD + 
			 paramYTD + confirmTD + deleteTD + "</tr>");
		 
				  $(".conditionDelete").each( function() {
				  $(this).click(function() {
				 if($(this).parent().parent().attr("save") != null) {
					 GameRuleService.deleteConditionForTrigger($(this).parent().parent().attr("conditionID"));
				 } 
					 $(this).parent().parent().remove();
				 
			 });
				 });
	}
	
}

 function createNewGameCB(data) {
	 $("#createGameModalDialog").dialog("close");
	 $("#gameTabMessage").writeAlert("Game create successfully.").fadeIn("slow").delay(5000).fadeOut(
	   "slow");
	 var gOption = document.createElement("OPTION");
	 gOption.value = data;
	 gOption.text = newGame.gameName;
	 $("#gameList")[0].options.add(gOption, 0);
	 $("#gameList")[0].options[0].selected = true;
	 $("#gameList")[0].selectedIndex = 0;
 }

 function modifyGameDetailsCB(data) {

	 $("#gameTabMessage").writeAlert("Modify game details successfully.").fadeIn("slow").delay(5000)
	   .fadeOut("slow");
	 for ( var i = 0; i < $("#gameList")[0].length; ++i) {
		 if ($("#gameList")[0].options[i].value == currentGameID) {
			 $("#gameList")[0].options[i].text = $("#edGameName").val();
		 }
	 }
 }

 function retrieveGameListCB(data) {
	 for ( var i = 0; i < data.length; i++) {
		 var gOption = document.createElement("OPTION");
		 gOption.value = data[i].gameID;
		 gOption.text = data[i].gameName;
		 $("#gameList")[0].options.add(gOption);
	 }

 }

 function loadGameDetailsCB(data) {
	 //Unlock the other panels when the game is loaded.
	 $("#tabs").tabs("option", "disabled", []);
	 currentGameID = data.gameID;
	 currentGameDetails = data;

	 $("#edGameName").val(data.gameName);
	 $("#edPublishTitle").val(data.publishTitle);
	 $("#edPublishDescription").val(data.publishDescription);
	 $("#edInternalDescription").val(data.internalDescription);
	 $("#edIntroduction").val(data.introduction);
	 $("#edEnding").val(data.ending);
	 $("#designStatus").text(data.designStatus);
	 $("#designStatus").val(data.designStatus);

 }

 function retrieveItemListCB(data) {
	 var itemsTable = $("#itemsTable");

	 for ( var i = 0; i < data.length; i++) {
		 var locID = "";
		 if (data[i].location != null)
			 locID = data[i].location.locationID;
		 var itemObjString = "<tr><td class='itemRow' id='"+data[i].itemID+
		 "' locationID='"+locID+
		 "'><img class='draggableGameObj' type='item'src='item.png' /><b>"
		   + data[i].itemTitle + "</b></td></tr>";
		 var itemObj = $(itemObjString).prependTo(itemsTable);
		 var itemRow = $(".itemRow").first();
		 
		 currentItemHeaders.push({id:data[i].itemID,title:data[i].itemTitle});

		 itemRow.click(function() {
			 $(".itemRow").removeClass("selectedItemRow");
			 $(this).addClass("selectedItemRow");
			 var itemRow = $(this);
			 $(".gameObjPropertyPanel").hide();
			 $("#itemPropertySubPanel").show();

			 ItemService.readItemDetails($(this).attr("id"), function(data) {
				 readItemDetailsCB(data, itemRow);
			 });
		 });
		 if (locID != "") {
			 var ll = new google.maps.LatLng(data[i].location.lat, data[i].location.lng);
			 var marker = new google.maps.Marker({ gameObjectID: data[i].itemID, objType: "item",position : ll, locationID : locID, clickable : true,
			  draggable : true, title : data[i].itemTitle, map : map, icon : 'item.png' });
			 addListenersForMarker(marker);
			 curMapItemMarkers.push(marker);
		 }
	 }

	 $(".draggableGameObj").each(makeDraggable);
	 $(".draggableGameObj").each(makeDBClickTrackable);
 }
 
function retrieveQuestListForInitialCB(data) {
	 var questsTable = $("#questsTable");
	 currentQuestNum  = data.length;
	 for ( var i = 0; i < data.length; i++) {
		 var locID = "";
		 if (data[i].location != null)
			 locID = data[i].location.locationID;
		 var questObjString = "<tr><td class='questRow' id='"+data[i].questID+
		 "' locationID='"+locID+
		 "'><img class='draggableGameObj' type='quest'src='quest.png' /><b>"
		   + data[i].questTitle + "</b></td></tr>";
		 var questObj = $(questObjString).prependTo(questsTable);
		 var questRow = $(".questRow").first();
		 
		 currentQuestHeaders.push({id:data[i].questID,title:data[i].questTitle});
		 
		 var questOrderStr = "<li questIDInTable='"+data[i].questID+"'"+ 
		 " questOrderInTable='"+ data[i].questOrder+"'"+
		 " class='ui-state-default'><span class='ui-icon ui-icon-arrowthick-2-n-s'>"+
		 "</span><b>"+data[i].questTitle+"</b></li>";
		 
		 $(questOrderStr).appendTo($("#questOrderTable"));

		 questRow.click(function() {
			 $(".questRow").removeClass("selectedQuestRow");
			 $(this).addClass("selectedQuestRow");
			 var questRow = $(this);
			 $(".gameObjPropertyPanel").hide();
			 $("#questPropertySubPanel").show();

			 QuestService.readQuestDetails($(this).attr("id"), function(data) {
				 readQuestDetailsCB(data, questRow);
			 });
		 });
		 if (locID != "") {
			 var ll = new google.maps.LatLng(data[i].location.lat, data[i].location.lng);
			 var marker = new google.maps.Marker({ gameObjectID: data[i].questID,objType: "quest",position : ll, locationID : locID, clickable : true,
			  draggable : true, title : data[i].questTitle, map : map, icon : 'quest.png' });
			 addListenersForMarker(marker);
			 curMapQuestMarkers.push(marker);
		 }
	 }
	 $( "#questOrderTable" ).sortable({update: function(event,ui) {
		 //todo
	 }});
	 $( "#questOrderTable" ).disableSelection();
	 $(".draggableGameObj").each(makeDraggable);
	 $(".draggableGameObj").each(makeDBClickTrackable);
 }

function retrieveQuestListWhenOrderingCB(data) {
	 currentQuestNum  = data.length;
	 $("#questOrderTable").html("");
	 for ( var i = 0; i < data.length; i++) {
		 var questOrderStr = "<li questIDInTable='"+data[i].questID+"'"+ 
		 " questOrderInTable='"+ data[i].questOrder+"'"+
		 " class='ui-state-default'><span class='ui-icon ui-icon-arrowthick-2-n-s'>"+
		 "</span><b>"+data[i].questTitle+"</b></li>";
		 
		 $(questOrderStr).appendTo($("#questOrderTable"));

	 }
	 
	 $( "#questOrderTable" ).sortable({update: function(event,ui) {
		 //todo
	 }});
	 $( "#questOrderTable" ).disableSelection();
}
 
 function retrieveNPCListCB(data) {
	 var npcsTable = $("#npcsTable");
	 var npcsSimpleTable = $("#npcsSimpleTable");

	 for ( var i = 0; i < data.length; i++) {
		 var locID = "";
		 if (data[i].location != null)
			 locID = data[i].location.locationID;
		 var npcObjString = "<tr><td class='npcRow' id='"+data[i].npcID+
		 "' locationID='"+locID+
		 "'><img class='draggableGameObj' type='npc'src='npc.png' /><b>"
		   + data[i].npcName + "</b></td></tr>";
		   
		 var npcObjSimpleString = "<tr><td class='npcSimpleRow' refNPCID='"+data[i].npcID+
		 "' openDialog='0'><b>"
		   + data[i].npcName + "</b></td></tr>";
		 var npcObj = $(npcObjString).prependTo(npcsTable);
		 var npcSimpleObj = $(npcObjSimpleString).prependTo(npcsSimpleTable);
		 var npcRow = $(".npcRow").first();
		 var npcSimpleRow = $(".npcSimpleRow").first();
		 
		 currentNPCHeaders.push({id:data[i].npcID,title:data[i].npcName});

		 npcRow.click(function() {
			 $(".npcRow").removeClass("selectedNPCRow");
			 $(this).addClass("selectedNPCRow");
			 var npcRow = $(this);
			 $(".gameObjPropertyPanel").hide();
			 $("#npcPropertySubPanel").show();

			 NPCService.readNPCDetails($(this).attr("id"), function(data) {
				 readNPCDetailsCB(data, npcRow);
			 });
		 });
		 
		 	npcSimpleRow.click(function() {
			 $(".npcSimpleRow").removeClass("selectedNPCSimpleRow");
			 $(this).addClass("selectedNPCSimpleRow");
			 currentEdittingDialogNPCID = $(this).attr("refNPCID");
			 if($(this).attr("openDialog") == "0") {
				 dialogTreeRenderForNPC($(this).attr("refNPCID"));
				 $(this).attr("openDialog","1");
			 }
			 $("#dialogfrom"+$(this).attr("refNPCID")).parent().parent().toggle(500);

			 
		 });


		 if (locID != "") {
			 var ll = new google.maps.LatLng(data[i].location.lat, data[i].location.lng);
			 var marker = new google.maps.Marker({ gameObjectID: data[i].npcID,objType:"npc",position : ll, locationID : locID, clickable : true,
			  draggable : true, title : data[i].npcName, map : map, icon : 'npc.png' });
			 addListenersForMarker(marker);
			 curMapNPCMarkers.push(marker);
		 }
	 }

	 $(".draggableGameObj").each(makeDraggable);
	 $(".draggableGameObj").each(makeDBClickTrackable);
 }
 
 
/* Part 2: Script Part2: for map tab*/
	var map;
 var latlng;
 var overlay;

 //map tab init
 $(document)
   .ready(
     function() {
	     $(".gameObjPropertyPanel").hide();
	
	     $("#openQuestOrderPanelBtn").click(function() {
	    	 if($("#questOrderPanel").dialog("isOpen")){
	    		 $("#questOrderPanel").dialog("close");
	    		 $("#openQuestOrderPanelBtn").button({icons:{primary: ""}});
	    	 } else {
		    	 $("#questOrderPanel").dialog("open");
		    	 $("#openQuestOrderPanelBtn").button({icons:{primary: "ui-icon-check"}});
	    	 }
	     });
	     
	     
		$("#modifyQuestOrderInTableBtn").click(function() {
			
			var questIDs = new Array();
			$("#questOrderTable li").each(function() {
				questIDs.push($(this).attr("questIDInTable"));
			});
			QuestService.modifyQuestOrderForGame(questIDs,function() {
			       $("#mapTabMessage").writeAlert("Modified Sucessfully").fadeIn("slow").delay(3500)
			         .fadeOut("slow");
			});
		});
		
		$("#reloadQuestOrderInTableBtn").click(function() {
			QuestService.retrieveQuestList(currentGameID, retrieveQuestListWhenOrderingCB);
		});


	     $("#createItemBtn")
	       .click(
	         function() {
		         var itemsTable = $("#itemsTable");
		         var itemObj = $(
		           "<tr><td class='itemRow' id='' locationID=''><img class='draggableGameObj' type='item'src='item.png' /><b>UntitledItem</b></td></tr>")
		           .prependTo(itemsTable);
		         var itemRow = $(".itemRow").first();
		         $(".itemRow").removeClass("selectedItemRow");
		         itemRow.addClass("selectedItemRow");

		         $(".selectedItemRow .draggableGameObj").each(makeDraggable);
		         $(".selectedItemRow .draggableGameObj").each(makeDBClickTrackable);

		         var item = { title : "UntitledItem", gameID : currentGameID, pickable : "t" };

		         var proxyCB = function(data) {
		        	 itemRow.attr("id",data);
		        	 currentItemHeaders.push({id:data,title:"UntitledItem"});
		        	 
		         };

		         ItemService.createItemWithoutLocation(item, proxyCB);

		         $(".gameObjPropertyPanel").hide();
		         $("#itemPropertySubPanel").show();

		         $("#edItemTitle").val("UntitledItem");
		         $("#edItemTitle").trigger("focus").trigger("select");

		         itemRow.click(function() {
			         $(".itemRow").removeClass("selectedItemRow");
			         $(this).addClass("selectedItemRow");
			         $(".gameObjPropertyPanel").hide();
			         $("#itemPropertySubPanel").show();
			         var itemRow = $(this);
			         ItemService.readItemDetails($(this).attr("id"), function(data) {
				         readItemDetailsCB(data, itemRow);
			         });
		         });

	         });
	       
	      $("#createQuestBtn")
	       .click(
	         function() {
		         var questsTable = $("#questsTable");
		         var questObj = $(
		           "<tr><td class='questRow' id='' locationID=''><img class='draggableGameObj' type='quest'src='quest.png' /><b>UntitledQuest</b></td></tr>")
		           .prependTo(questsTable);
		         var questRow = $(".questRow").first();
		         $(".questRow").removeClass("selectedQuestRow");
		         questRow.addClass("selectedQuestRow");

		         $(".selectedQuestRow .draggableGameObj").each(makeDraggable);
		         $(".selectedQuestRow .draggableGameObj").each(makeDBClickTrackable);

		         currentQuestNum++;
		         var quest = { title : "UntitledQuest", gameID : currentGameID, questOrder : currentQuestNum };
		         
		         var proxyCB = function(data) {
		        	 questRow.attr("id",data);
	         		 var questOrderStr = "<li questIDInTable='"+data+"'"+ 
	        		 " questOrderInTable='"+ currentQuestNum + "'"+
	        		 " class='ui-state-default'><span class='ui-icon ui-icon-arrowthick-2-n-s'></span><b>UntitledQuest</b></li>"; 
	        		 $(questOrderStr).appendTo($("#questOrderTable"));
	        		 currentQuestHeaders.push({id:data,title:"UntitledQuest"});
		         };

		         QuestService.createQuestWithoutLocation(quest, proxyCB);
		         

		         $(".gameObjPropertyPanel").hide();
		         $("#questPropertySubPanel").show();

		         $("#edQuestTitle").val("UntitledQuest");
		         $("#edQuestTitle").trigger("focus").trigger("select");

		         questRow.click(function() {
			         $(".questRow").removeClass("selectedQuestRow");
			         $(this).addClass("selectedQuestRow");
			         $(".gameObjPropertyPanel").hide();
			         $("#questPropertySubPanel").show();
			         var questRow = $(this);
			         QuestService.readQuestDetails($(this).attr("id"), function(data) {
				         readQuestDetailsCB(data, questRow);
			         });
		         });

	         });
	     
	  $("#createNPCBtn")
      .click(
        function() {
         var npcsTable = $("#npcsTable");
         var npcsSimpleTable = $("#npcsSimpleTable");
         var npcObj = $(
           "<tr><td class='npcRow' id='' locationID=''><img class='draggableGameObj' type='npc'src='npc.png' /><b>UntitledNPC</b></td></tr>")
           .prependTo(npcsTable);
           
         var npcSimpleObj = $(
           "<tr><td class='npcSimpleRow' refNPCID='' openDialog='0'><b>UntitledNPC</b></td></tr>")
           .prependTo(npcsSimpleTable);
         var npcRow = $(".npcRow").first();
         var npcSimpleRow = $(".npcSimpleRow").first();
         $(".npcRow").removeClass("selectedNPCRow");
         npcRow.addClass("selectedNPCRow");

         $(".selectedNPCRow .draggableGameObj").each(makeDraggable);
         $(".selectedNPCRow .draggableGameObj").each(makeDBClickTrackable);

         var npc = { name : "UntitledNPC", gameID : currentGameID, chattable : "t" };

         var proxyCB = function(data) {
        	 npcSimpleRow.attr("refNPCID",data);
        	 npcRow.attr("id",data);
        	 currentNPCHeaders.push({id:data,title:"UntitledNPC"});
         };

         NPCService.createNPCWithoutLocation(npc, proxyCB);

         $(".gameObjPropertyPanel").hide();
         $("#npcPropertySubPanel").show();

         $("#edNPCName").val("UntitledNPC");
         $("#edNPCName").trigger("focus").trigger("select");

         npcRow.click(function() {
	         $(".npcRow").removeClass("selectedNPCRow");
	         $(this).addClass("selectedNPCRow");
	         $(".gameObjPropertyPanel").hide();
	         $("#npcPropertySubPanel").show();
	         var npcRow = $(this);
	         NPCService.readNPCDetails($(this).attr("id"), function(data) {
		         readNPCDetailsCB(data, npcRow);
	         });
         });
         
             npcSimpleRow.click(function() {
            	 
	         $(".npcSimpleRow").removeClass("selectedNPCSimpleRow");
	         $(this).addClass("selectedNPCSimpleRow");
			 if($(this).attr("openDialog") == "0") {
				 dialogTreeRenderForNPC($(this).attr("refNPCID"));
				 $(this).attr("openDialog","1");
			 }
			 $("#dialogfrom"+$(this).attr("refNPCID")).parent().parent().toggle(500);
         });

        });

	     $("#modifyItemBtn").click(
	       function() {
		       var modRow = $(".selectedItemRow:first");
		       var modRowTitle = modRow.children("b").first();
		       var modID = modRow.attr("id");
		       var newTitle = $("#edItemTitle").val();
		       
		       var pickable;
		       if($("#itemPickableCheck").attr("checked") == "checked"){
		    	   pickable = "t";
		       } else pickable = "f";
		       var modItem = { itemID : modID, gameID : currentGameID, title : newTitle,
		        displayText : $("#edItemDisplayText").val(),
		        pickable  : pickable };
		       
		        for(var i = 0 ; i < currentItemHeaders.length; ++i) {
		        	if(currentItemHeaders[i].id == modID) {
		        		currentItemHeaders[i].title = newTitle;
		        	}
		        }
		        
		        for(var i = 0 ; i < curMapItemMarkers.length; ++i) {
		        	if(curMapItemMarkers[i].gameObjectID == modID) {
		        		curMapItemMarkers[i].setTitle(newTitle);
		        	}
		        }


		       ItemService.modifyItemWithoutLocation(modItem, function() {
			       modRowTitle.text(newTitle);
			       $("#mapTabMessage").writeAlert("Modified Sucessfully").fadeIn("slow").delay(3500)
			         .fadeOut("slow");
		       });
	       });
	     
	     $("#modifyQuestBtn").click(
	       function() {
		       var modRow = $(".selectedQuestRow:first");
		       var modRowTitle = modRow.children("b").first();
		       var modID = modRow.attr("id");
		       var newTitle = $("#edQuestTitle").val();
		       var modQuest = { questID : modID, gameID : currentGameID, title : newTitle,
		        startText : $("#edQuestStartText").val(),
		       completeText : $("#edQuestCompleteText").val() };
		       
		       for(var i = 0 ; i < currentQuestHeaders.length; ++i) {
		        	if(currentQuestHeaders[i].id == modID) {
		        		currentQuestHeaders[i].title = newTitle;
		        	}
		        }
		       
		        for(var i = 0 ; i < curMapQuestMarkers.length; ++i) {
		        	if(curMapQuestMarkers[i].gameObjectID == modID) {
		        		curMapQuestMarkers[i].setTitle(newTitle);
		        	}
		        }

		       QuestService.modifyQuestWithoutLocation(modQuest, function() {
			       modRowTitle.text(newTitle);
			       $("#mapTabMessage").writeAlert("Modified Sucessfully").fadeIn("slow").delay(3500)
			         .fadeOut("slow");
			         var a = $("[questOrderInTable="+modID+"]");
			         var b = a.text();
			       $("[questIDInTable="+modID+"]").children("b").first().text(newTitle);
		       });
	       });
	     
	     $("#modifyNPCBtn").click(
	       function() {
		       var modRow = $(".selectedNPCRow:first");
		       var modRowName = modRow.children("b").first();
		       var modID = modRow.attr("id");
		       var newName = $("#edNPCName").val();
		       var chattable;
		       if($("#npcChattableCheck").attr("checked") == "checked"){
		    	   chattable = "t";
		       } else chattable = "f";
		       var modNPC = { npcID : modID, gameID : currentGameID, name : newName,
		        greeting : $("#edNPCGreeting").val(),
		       chattable: chattable };
		       
		        for(var i = 0 ; i < currentNPCHeaders.length; ++i) {
		        	if(currentNPCHeaders[i].id == modID) {
		        		currentNPCHeaders[i].title = newName;
		        	}
		        }
		        
		        for(var i = 0 ; i < curMapNPCMarkers.length; ++i) {
		        	if(curMapNPCMarkers[i].gameObjectID == modID) {
		        		curMapNPCMarkers[i].setTitle(newName);
		        	}
		        }

		       NPCService.modifyNPCWithoutLocation(modNPC, function() {
			       modRowName.text(newName);
			       $("#mapTabMessage").writeAlert("Modified Sucessfully").fadeIn("slow").delay(3500)
			         .fadeOut("slow");
		       });
		       $("[refNPCID="+modID+"]").children("b").first().text(newName);
	       });
	     
	     $("#reloadItemBtn").click(function() {
	     	var selectedItemRow = $(".selectedItemRow").first();
	     	ItemService.readItemDetails(selectedItemRow.attr("id"), function(data) {
	  				 readItemDetailsCB(data, selectedItemRow);
	  			 });
	     	
	     });
	     
	      $("#reloadQuestBtn").click(function() {
	     	var selectedQuestRow = $(".selectedQuestRow").first();
	     	QuestService.readQuestDetails(selectedQuestRow.attr("id"), function(data) {
	  				 readQuestDetailsCB(data, selectedQuestRow);
	  			 });
	     	
	     });
	     
	     $("#reloadNPCBtn").click(function() {
	     	var selectedNPCRow = $(".selectedNPCRow").first();
	     	NPCService.readNPCDetails(selectedNPCRow.attr("id"), function(data) {
	  				 readNPCDetailsCB(data, selectedNPCRow);
	  			 });
	     	
	     });
	     
	     $("#deleteItemBtn").click(function() {
	     	var itemID = $(".selectedItemRow ").first().attr("id");
	     	var locID = $(".selectedItemRow ").first().attr("locationID");
	     	
	      for(var i = 0 ; i < currentItemHeaders.length; ++i) {
		        	if(currentItemHeaders[i].id == itemID) {
		        		currentItemHeaders.remove(currentItemHeaders[i]);
		        	}
		        }
	      
	      	GameRuleService.deleteAllTriggersAndConditions(itemID);
	     	ItemService.deleteItemAndLocation(itemID,function() {
	     		$("#itemPropertySubPanel").hide();
	     		for(var i = 0;i < curMapItemMarkers.length;++i) {
	     			if(curMapItemMarkers[i].locationID == locID) {
	     				curMapItemMarkers[i].setMap(null);
	 	 			    curMapItemMarkers.remove(curMapItemMarkers[i]);
	     			}
	     		}
	     		$(".selectedItemRow ").parent().remove();
	     		
	     	});
	     });
	     
	      $("#deleteQuestBtn").click(function() {
	     	var questID = $(".selectedQuestRow ").first().attr("id");
	     	var locID = $(".selectedQuestRow ").first().attr("locationID");
	     	
	     		      for(var i = 0 ; i < currentQuestHeaders.length; ++i) {
		        	if(currentQuestHeaders[i].id == questID) {
		        		currentQuestHeaders.remove(currentQuestHeaders[i]);
		        	}
		        }

		    GameRuleService.deleteAllTriggersAndConditions(questID);
	     	QuestService.deleteQuestAndLocation(questID,function() {
	     		$("#questPropertySubPanel").hide();
	     		for(var i = 0;i < curMapQuestMarkers.length;++i) {
	     			if(curMapQuestMarkers[i].locationID == locID) {
	     				curMapQuestMarkers[i].setMap(null);
	 	 			    curMapQuestMarkers.remove(curMapQuestMarkers[i]);
	     			}
	     		}
	     		$(".selectedQuestRow ").parent().remove();
	     		$("[questIDInTable="+questID+"]").remove();
	     	});
	     });
	     
	     $("#deleteNPCBtn").click(function() {
	     	var npcID = $(".selectedNPCRow ").first().attr("id");
	     	var locID = $(".selectedNPCRow ").first().attr("locationID");
	     	
	      for(var i = 0 ; i < currentNPCHeaders.length; ++i) {
		        	if(currentNPCHeaders[i].id == npcID) {
		        		currentNPCHeaders.remove(currentNPCHeaders[i]);
		        	}
		        }
	     	
		    GameRuleService.deleteAllTriggersAndConditions(npcID);
	     	NPCService.deleteNPCAndLocation(npcID,function() {
	     		$("#npcPropertySubPanel").hide();
	     		for(var i = 0;i < curMapNPCMarkers.length;++i) {
	     			if(curMapNPCMarkers[i].locationID == locID) {
	     				curMapNPCMarkers[i].setMap(null);
	 	 			    curMapNPCMarkers.remove(curMapNPCMarkers[i]);
	     			}
	     		}
	     		$(".selectedNPCRow ").parent().remove();
	     		$("[refNPCID="+npcID+"]").parent().remove();
	     	});
	     });

	     $("#gameObjsAccordionsPanel").accordion().dialog(
	       { autoOpen : false, resizable : false, closeOnEscape : false, hide : "slow", show : "slow",
	        width : 250, height : 400, title : "Game Objects", position : [ 740, 60 ],
	        open : function(event, ui) {
		        $(".ui-dialog-titlebar-close").hide();
		        //$("#gameObjsAccordions").accordion({ autoHeight: true });	
	        } });

	     $("#mapPropertyPanel").dialog(
	       { autoOpen : false, resizable : false, closeOnEscape : false, hide : "slow", show : "slow",
	        width : 800, height : 220, modal : false, title : "Properties", position : [ 20, 350 ],
	        open : function(event, ui) {
		        $(".ui-dialog-titlebar-close").hide();
	        } });
	     
	       $("#questOrderPanel").dialog(
	       { autoOpen : false, resizable : false, closeOnEscape : false, hide : "slow", show : "slow",
	        width : 350, height : 400, modal : false, title : "Quest Order", position : [ 100, 100 ]
	      });

	     //helper clone solve problem of cloning. appendTo solve the problem of invisible when dragging objs out of the accordions.
	     $(".draggableGameObj").each(makeDraggable);

     });

 function readItemDetailsCB(data, arg) {
	 arg.attr("locationID", data.locationID);
	 $("#edItemDisplayText").val(data.displayText);
	 $("#edItemTitle").val(data.title);
	 if(data.pickable == "t") {
		 $("#itemPickableCheck").attr("checked","true");
	 } else{
		 $("#itemPickableCheck").removeAttr("checked");
	 }
 }
 
function readQuestDetailsCB(data, arg) {
	 arg.attr("locationID", data.locationID);
	 $("#edQuestTitle").val(data.title);
	 $("#edQuestStartText").val(data.startText);
	 $("#edQuestCompleteText").val(data.completeText);
 }
 
 function readNPCDetailsCB(data, arg) {
	 arg.attr("locationID", data.locationID);
	 $("#edNPCGreeting").val(data.greeting);
	 $("#edNPCName").val(data.name);
	 if(data.chattable == "t") {
		 $("#npcChattableCheck").attr("checked","true");
	 } else{
		 $("#npcChattableCheck").removeAttr("checked");
	 }
 }

 function makeDBClickTrackable() {
	 $(this).dblclick(function() {
	 	var refMarkers;
	 	if($(this).attr("type")=="item") refMarkers = curMapItemMarkers;
	 	else if($(this).attr("type")=="npc") refMarkers = curMapNPCMarkers;
	 	else if($(this).attr("type")=="quest") refMarkers = curMapQuestMarkers;
	 	else return;
	
		 if ($(this).parent().attr("locationID") != null && $(this).parent().attr("locationID") != "") {
			 for ( var i = 0; i < refMarkers.length; ++i) {
				 if (refMarkers[i].locationID == $(this).parent().attr("locationID")) {
					 map.panTo(refMarkers[i].getPosition());
					 refMarkers[i].setAnimation(google.maps.Animation.BOUNCE);

					 var temp = refMarkers[i];
					 setTimeout(function() {
						 temp.setAnimation(null);
					 }, 3500);
				 }
			 }
		 }
	 });
 }

 function addListenersForMarker(marker) {

	 google.maps.event.addListener(marker, "drag", function(event) {
		 var point = marker.getPosition();
		 map.panTo(point);
	 });

	 google.maps.event.addListener(marker, "dragend", function(event) {
		 var ll = marker.getPosition();
		 var location = { locationID : marker.locationID, lat : ll.lat(), lng : ll.lng(), error : 5 };
		 LocationService.updateLocation(location);
	 });

	 marker.infoWindowNum = 0;

	 google.maps.event.addListener(marker, "dblclick", function(event) {
		 var point = marker.getPosition();
		 $("#mapTabMessage").writeAlert(marker.getTitle()).fadeIn("slow").delay(3500).fadeOut("slow");

		 if (marker.infoWindowNum == 0) {
		 	marker.infoWindowNum++;
			 //marker has already filled in the locationID attribute
			 var infoWindow = new google.maps.InfoWindow(
			   { content : "<b>Delete this location</b><br><div id="+marker.locationID+"><button class='deleteLocBtn'>Delete Me</button></div>" });

			 google.maps.event.addListener(infoWindow, 'domready', function() {
				 $("#"+marker.locationID+" .deleteLocBtn").button();
				 $("#"+marker.locationID+" .deleteLocBtn").on("click", function() {
					 if(marker.objType == "item") {
					 	var itemID;
						 $(".itemRow").each(function(){
						 	if($(this).attr("locationID") == marker.locationID) {
						 		$(this).attr("locationID","");
						 		itemID = $(this).attr("id");
						 	}
						 });
						 ItemService.deleteLocation(itemID,marker.locationID);
						 marker.setMap(null);
						 curMapItemMarkers.remove(marker);
						 
					 }
					 
					 if(marker.objType == "quest") {
					 	var questID;
						 $(".questRow").each(function(){
						 	if($(this).attr("locationID") == marker.locationID) {
						 		$(this).attr("locationID","");
						 		questID = $(this).attr("id");
						 	}
						 });
						 QuestService.deleteLocation(questID,marker.locationID);
						 marker.setMap(null);
						 curMapQuestMarkers.remove(marker);
						 
					 }
					 
					 if(marker.objType == "npc") {
					 	var npcID;
						 $(".npcRow").each(function(){
						 	if($(this).attr("locationID") == marker.locationID) {
						 		$(this).attr("locationID","");
						 		npcID = $(this).attr("id");
						 	}
						 });
						 NPCService.deleteLocation(npcID,marker.locationID);
						 marker.setMap(null);
						 curMapNPCMarkers.remove(marker);
						 
					 }
					 $("#mapTabMessage").writeAlert("Delete location successfully.").fadeIn("slow").delay(3500).fadeOut("slow");
				 });
			 });
			 infoWindow.open(map, marker);

			 google.maps.event.addListener(infoWindow, 'closeclick', function() {
				 marker.infoWindowNum = 0;
			 });

		 }
	 });

 }

 function makeDraggable() {
 	 var dragObjType = $(this).attr("type");
	   var refMarkers;
	   if(dragObjType == "item") refMarkers = curMapItemMarkers;
	   else if(dragObjType == "npc") refMarkers = curMapNPCMarkers;
	   else if(dragObjType == "quest") refMarkers = curMapQuestMarkers;
	   else return;
	 $(this).draggable(
	   {
	    helper : 'clone',
	    appendTo : 'body',
	    stop : function(e) {
		    var locID = $(this).parent().attr("locationID");
		    if (locID != null && locID != "") {
			    $("#mapTabMessage").writeError(
			      "Cannot drag into the map because it has already been in the map").fadeIn("slow").delay(
			      3500).fadeOut("slow");
			    for ( var i = 0; i < refMarkers.length; ++i) {
				    if (refMarkers[i].locationID == locID) {
					    map.panTo(refMarkers[i].getPosition());
					    refMarkers[i].setAnimation(google.maps.Animation.BOUNCE);
					    var infowindow = new google.maps.InfoWindow(
					      { content : "<b>Already dragged here!!!</b><br>" });
					    infowindow.open(map, refMarkers[i]);

					    var temp = refMarkers[i];
					    setTimeout(function() {
						    temp.setAnimation(null);
					    }, 3000);
				    }
			    }
			    return;
		    }

		    var imageType = dragObjType + ".png";
		    var point = new google.maps.Point(e.originalEvent.clientX, e.originalEvent.clientY);
		    var proj = overlay.getProjection();
		    var ll = proj.fromContainerPixelToLatLng(point);
		    var marker = new google.maps.Marker({ gameObjectID: $(this).parent().attr("id"),position : ll, objType:dragObjType,
		    // animation:DROP,
		    clickable : true, draggable : true, title : $(this).next().text(), map : map, icon : imageType });

		    var selected = $(this).parent().first();
		    var location = { lat : ll.lat(), lng : ll.lng(), error : 5 };

		    if (dragObjType == "item") {
			    var itemID = selected.attr("id");   
			    ItemService.createLocation(location, itemID, function(data) {
				    selected.attr("locationID", data);
				    marker.locationID = data;
				    refMarkers.push(marker);
			    });
		    } else if(dragObjType == "npc") {
		    	var npcID = selected.attr("id");
			    NPCService.createLocation(location, npcID, function(data) {
				    selected.attr("locationID", data);
				    marker.locationID = data;
				    refMarkers.push(marker);
			    });
		    } else if(dragObjType == "quest") {
		    	var questID = selected.attr("id");
			    QuestService.createLocation(location, questID, function(data) {
				    selected.attr("locationID", data);
				    marker.locationID = data;
				    refMarkers.push(marker);
			    });
		    }

		    addListenersForMarker(marker);

	    } });
 }

 function GameMap(map) {
	 this.setMap(map);
 }
 GameMap.prototype = new google.maps.OverlayView();
 GameMap.prototype.draw = function() {
	 if (!this.ready) {
		 this.ready = true;
		 google.maps.event.trigger(this, 'ready');
	 }
 };
 GameMap.prototype.onAdd = function() {
	 // the Overlay dummy is ready and can be called upon
	 delayedInit();
 };

 function initialize() {
	 latlng = new google.maps.LatLng(53.4, -6.5);
	 var myOptions = { zoom : 12, center : latlng, mapTypeId : google.maps.MapTypeId.ROADMAP };
	 map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
	 overlay = new google.maps.OverlayView();
	 overlay.draw = function() {};
	 overlay.setMap(map);

	 var height = document.body.clientHeight - 50;
	 $("body").height(height);

	 $("#tabs-2").height(height - 50);
	 $("#map_canvas").height(height - 50);


 }

/*Part 4: for Dialog tab*/
	$(document).ready(
  function() {
  	
  
  	$("#modifyDNodeBtn").click(function() {
  		var newName = $("#edDNodeName").val();
  		var dNode = {
  		        dialogNodeID : $(".selectedDNode:first").attr("dNodeID"),
  				name:newName,
  				displayText : $("#edDNodeDisplayText").val()
  		};


  		if($("#dNodeTypeCheck").attr("checked") == "checked") {
  			dNode.nodeType = "finish";
  		} else {
  			dNode.nodeType = "progress";
  		}

  		if($("#dNodeDisplayRadio").attr("checked") == "checked") {
  			dNode.interactionType = "display";
  		} else if ($("#dNodeAnswerRadio").attr("checked") == "checked") {
  			dNode.interactionType = "answer";
  		} else if ($("#dNodeBranchRadio").attr("checked") == "checked") {
  			dNode.interactionType = "branch";
  		}
  		
  		DialogService.modifyDialogNodeDetails(dNode, function() {
		       $("#mapTabMessage").writeAlert("Modified Sucessfully").fadeIn("slow").delay(3500)
		         .fadeOut("slow");
		         $(".selectedDNode:first ").text(newName);
  		});
  	});
  	
  	$("#addBranchBtn").click(function() {
  		if(currentBranchNum == 4) {
  			$("#mapTabMessage").writeError(
		      "Maximum four branches for a dialog node").fadeIn("slow").delay(
		      3500).fadeOut("slow");
  			return;
  		} 
  		var selectedDialogNode = $(".selectedDNode:first");
  		
  		var createNodeNameNum = currentBranchNum + 1;
  		var createNodeName = "Branch " + createNodeNameNum;
  		DialogService.createNewBranchForDialogNode(selectedDialogNode.attr("dNodeID"),createNodeName,function(data) {
  			var branch = $("<li ><span class='folder' dNodeID='"+data[0]+"'>"+createNodeName+"</span><ul>");
  			selectedDialogNode.siblings("ul").append(branch);
  			selectedDialogNode.siblings("ul").treeview();
  			$("span[dNodeID]").unbind("click");
  			$("span[dNodeID]").css("cursor","pointer");
  			$("span[dNodeID]").click(function() {
  				$(".selectedDNode:first").removeClass("selectedDNode");
  				$(this).addClass("selectedDNode");
  				$("#edDNode1Answer").val("");
  				$("#edDNode2Answer").val("");
  				$("#edDNode3Answer").val("");
  				$("#edDNode4Answer").val("");
  				DialogService.readDialogNodeDetails($(this).attr("dNodeID"), readDialogNodeDetailsCB);
  				DialogService.retrieveBranchesForFromDialogNode($(this).attr("dNodeID"),retrieveBranchesForFromDialogNodeCB);
  			});
  			currentBranchNum++;
  			if(currentBranchNum > 3) $("#branch4").show().attr("branchID",data[1]);
  			else if(currentBranchNum > 2) $("#branch3").show().attr("branchID",data[1]);
  			else if(currentBranchNum > 1) $("#branch2").show().attr("branchID",data[1]);
  			else if(currentBranchNum > 0) $("#branch1").show().attr("branchID",data[1]);
  		});
  		
  	});
  	
  	$("#reloadDNodeBtn").click(function() {
  		var modID = $(".selectedDNode:first").attr("dNodeID");
  		$("#edDNode1Answer").val("");
		$("#edDNode2Answer").val("");
		$("#edDNode3Answer").val("");
		$("#edDNode4Answer").val("");
		DialogService.readDialogNodeDetails(modID, readDialogNodeDetailsCB);
		DialogService.retrieveBranchesForFromDialogNode(modID,retrieveBranchesForFromDialogNodeCB);
  	});
  	
  	
  	$("#deleteDNodeBtn").click(function() {
  		if($(".selectedDNode:first").parent().parent().attr("id") != null) {
  			$("#mapTabMessage").writeError(
		      "At least one node for the dialog").fadeIn("slow").delay(
		      3500).fadeOut("slow");
  			return;
  		}
  		var dNodeID = $(".selectedDNode:first").attr("dNodeID");
  		DialogService.deleteDialogNodeAndChildren(dNodeID,function() {
  			//$("[dNodeID="+dNodeID+"]").siblings("ul").html("");
  			$("[dNodeID="+dNodeID+"]").parent().remove();
  			$("#mapTabMessage").writeAlert(
		      "Delete successfully").fadeIn("slow").delay(
		      3500).fadeOut("slow");
  		});
  	});
  	
  	
$("#dNodeContainedMediaBtn").click(function() {
	 if (!$("#uploadModalDialog").dialog("isOpen")) {
		 	$("#upload_frame").contents().find("#pic").attr("src","loading.gif");
			 $("#uploadModalDialog").dialog("open");
			 $("#uploadModalDialog").dialog("option", "position", "center");
			 $("#requestUpload").val("dNodeContainedMedia");
			 $("#gameObjID").val($(".selectedDNode:first").attr("dNodeID"));
			 MediaService.previewUploadImages( $("#requestUpload").val(),
			 		$("#gameObjID").val(),function(data) {
			 	$("#upload_frame").contents().find("#pic").attr("src",data);
			 });
		 }
});
  	
  	$("#modifyAnswer1Btn").click(function() {
  		var modAnswer = {
  		      orderID : $("#branch1").attr("branchID"),
  		      answer : $("#edDNode1Answer").val()
  		};
  		DialogService.modifyBranchDetails(modAnswer,modifyBranchDetailsCB); 	
  	});
  	
  	  	$("#modifyAnswer2Btn").click(function() {
  		var modAnswer = {
  		      orderID : $("#branch2").attr("branchID"),
  		      answer : $("#edDNode2Answer").val()
  		};
  		DialogService.modifyBranchDetails(modAnswer,modifyBranchDetailsCB); 	
  	});
  	  	
  	  	$("#modifyAnswer3Btn").click(function() {
  		var modAnswer = {
  		      orderID : $("#branch3").attr("branchID"),
  		      answer : $("#edDNode3Answer").val()
  		};
  		DialogService.modifyBranchDetails(modAnswer,modifyBranchDetailsCB); 	
  	});
  	  	
  	  	$("#modifyAnswer4Btn").click(function() {
  		var modAnswer = {
  		      orderID : $("#branch4").attr("branchID"),
  		      answer : $("#edDNode4Answer").val()
  		};
  		DialogService.modifyBranchDetails(modAnswer,modifyBranchDetailsCB); 	
  	});
  	
  	
   $("#npcDialogsPropertyPanel").dialog(
     { autoOpen : false, resizable : false, closeOnEscape : false, hide : "slow", show : "slow",
      width : 550, height : 550, modal : false, title : "Properties", position : [ 560, 50 ],
      open : function(event, ui) {
       $(".ui-dialog-titlebar-close").hide();
      } });
   
   $("#npcDialogsAccordionsPanel").accordion().dialog(
     { autoOpen : false, resizable : false, closeOnEscape : false, hide : "slow", show : "slow",
      width : 550, height : 550, title : "Select the Dialog", position : [ 20, 50 ],
      open : function(event, ui) {
       $(".ui-dialog-titlebar-close").hide();
      } });
   
  });
	
	  
function modifyBranchDetailsCB() {
	$("#mapTabMessage").writeAlert(
    "Modify answer successfully.").fadeIn("slow").delay(
    3500).fadeOut("slow");
}

	

/**
 * data is a tree structure 
 */
function dialogTreeRenderForNPC(npcID) {
	DialogService.retrieveDialogInTree(npcID,function(data) {
		var npcInitialTreeStr = treeConstructionRecursiveStr(data);
		var finalTreeStr = "<ul id='"+"dialogfrom"+npcID+"' class='filetree treeview-famfamfam'>"+
		npcInitialTreeStr + "</ul>";

		var finalTableStr = "<tr><td>" + finalTreeStr +"</tr></td>";
		var npcRow  = $("[refNPCID="+npcID+"]");
		$(finalTableStr).insertAfter(npcRow.parent());
		$("#"+"dialogfrom"+npcID).treeview({toggle: function() {
			console.log("%s was toggled.", $(this).find(">span").text());
		}});
		$("span[dNodeID]").unbind("click");
		$("span[dNodeID]").css("cursor","pointer");

		$("span[dNodeID]").click(function() {
			$(".selectedDNode:first").removeClass("selectedDNode");
			$(this).addClass("selectedDNode");
			$("#edDNode1Answer").val("");
			$("#edDNode2Answer").val("");
			$("#edDNode3Answer").val("");
			$("#edDNode4Answer").val("");
			DialogService.readDialogNodeDetails($(this).attr("dNodeID"), readDialogNodeDetailsCB);
			DialogService.retrieveBranchesForFromDialogNode($(this).attr("dNodeID"),retrieveBranchesForFromDialogNodeCB);
		});
	});
}

function treeConstructionRecursiveStr(data) {
	if(data != null) {
		var head  = "<li ><span class='folder' dNodeID='"+data.ID+"'>"+data.name+"</span><ul>";
		var body = "";
		if(data.node1!=null) body += treeConstructionRecursiveStr(data.node1);
		if(data.node2!=null) body += treeConstructionRecursiveStr(data.node2);
		if(data.node3!=null) body += treeConstructionRecursiveStr(data.node3);
		if(data.node4!=null) body += treeConstructionRecursiveStr(data.node4);
		body+=" "; 
		var tail = "</ul></li>";
		return head + body + tail;
	} else return "";
}

function readDialogNodeDetailsCB(data) {
	$("#edDNodeName").val(data.name);
	$("#edDNodeDisplayText").val(data.displayText);
	if(data.nodeType == "finish") {
		$("#dNodeTypeCheck").attr("checked","true");
	} else {
		$("#dNodeTypeCheck").removeAttr("checked");
	}
	$("[name='dNodeInteractionType']").removeAttr("checked");
	if(data.interactionType == "display") {
		$("#dNodeDisplayRadio").attr("checked","true");
	} else if(data.interactionType == "answer") {
		$("#dNodeAnswerRadio").attr("checked","true");
	} else if(data.interactionType == "branch") {
		$("#dNodeBranchRadio").attr("checked","true");
	}
}

function retrieveBranchesForFromDialogNodeCB(data) {
	$(".branches").hide();
	currentBranchNum = data.length;
	if(data.length > 3) {
		$("#branch4").show();
		$("#edDNode4Answer").val(data[3].answer);
		$("#branch4").attr("branchID",data[3].orderID);
	}
	if(data.length > 2) {
		$("#branch3").show();
		$("#edDNode3Answer").val(data[2].answer);
		$("#branch3").attr("branchID",data[2].orderID);
	}
	if(data.length > 1) {
		$("#branch2").show();
		$("#edDNode2Answer").val(data[1].answer);
		$("#branch2").attr("branchID",data[1].orderID);
	}
	if(data.length > 0) {
		$("#branch1").show();
		$("#edDNode1Answer").val(data[0].answer);
		$("#branch1").attr("branchID",data[0].orderID);
	} 
}
